import { Pool } from 'pg'
import { DependencyContainer } from 'tsyringe'
import { ROOT } from '@sker/core'
import { join } from 'path';
import * as db from 'zapatos/db';
let pool: Pool;
export function createPgPool(injector: DependencyContainer) {
    if (pool) return pool;
    const root = injector.resolve(ROOT)
    const jsonFile = join(`${root}`, 'data/plugins', `@sker/orm.json`)
    const config = require(jsonFile)
    const url = new URL(config.url)
    if (config.type !== 'postgres') {
        throw new Error(`config.type must be postgres`)
    }
    pool = new Pool({
        user: url.username,
        password: url.password,
        host: url.hostname,
        port: parseInt(url.port),
        database: url.pathname.replace('/', '')
    })
    return pool;
}
export interface IPgClientCallback<T> {
    (d: typeof db, pool: Pool): Promise<T>
}
export async function usePgClient<T>(injector: DependencyContainer, handler: IPgClientCallback<T>) {
    const pool = createPgPool(injector)
    const result = await handler(db, pool)
    return result;
}
export default usePgClient;